package xy.http.util;

import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import xy.http.config.OkHttpConfig;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;


public class OkHttpUtil {

    private static final Logger log = LoggerFactory.getLogger(OkHttpUtil.class);

    private OkHttpClient client;

    public OkHttpUtil(OkHttpClient client) {
        this.client = client;
    }

    /**
     * 执行
     *
     * @return
     */
    public String exec(Request request) {
        Response response = null;
        String result = null;
        try {
            // 执行请求
            response = client.newCall(request).execute();
            // 判断请求是否成功
            if (!response.isSuccessful()) {
                return "";
            }
            result = (Objects.requireNonNull( response.body().string().toString()));
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            log.error("执行请求异常");
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return "";
    }

    /**
     * GET URL已带请求参数
     *
     * @return
     */
    public String doGet(String url) {
        Request request = new Request.Builder().url(url).build();
        return exec(request);
    }

    /**
     * get 请求 拼接参数
     *
     * @param url
     * @param paramsMap
     * @return
     */
    public String doGetAndParams(String url, Map<String, String> paramsMap) {
        StringBuilder urlBuilder = new StringBuilder(url);
        if (paramsMap != null) {
            urlBuilder.append("?");
            try {
                for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
                    urlBuilder.append(URLEncoder.encode(entry.getKey(), "utf-8")).
                            append("=").
                            append(URLEncoder.encode(entry.getValue(), "utf-8")).
                            append("&");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            urlBuilder.deleteCharAt(urlBuilder.length() - 1);
        }
        Request request = new Request.Builder().url(urlBuilder.toString()).build();
        return exec( request);
    }


    /**
     * POST multipart/form-data表单请求
     *
     * @param url
     * @param paramsMap
     * @return
     */
    public String postFormData(String url, Map<String, String> paramsMap) {
        // 添加请求类型
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MediaType.parse("multipart/form-data"));

        //  创建请求的请求体
        for (String key : paramsMap.keySet()) {
            // 追加表单信息
            builder.addFormDataPart(key, paramsMap.get(key));
        }
        RequestBody body = builder.build();
        // 创建request, 表单提交
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        return exec(request);
    }

    /**
     * POST 以Form表单的形式提交
     *
     * @param url
     * @param paramsMap
     * @return
     */
    public String post(String url, Map<String, String> paramsMap) {
        // 创建请求的请求体
        FormBody.Builder builder = new FormBody.Builder();
        for (String key : paramsMap.keySet()) {
            // 追加表单信息
            builder.add(key, paramsMap.get(key));
        }
        RequestBody body = builder.build();
        // 创建request, 表单提交
        Request request = new Request.Builder()
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .url(url)
                .post(body)
                .build();
        return exec(request);
    }

    /**
     * POST json 格式提交
     *
     * @param url
     * @param json
     * @return
     */
    public String jsonPOst(String url, String json) {
        // 创建请求的请求体
        RequestBody body = RequestBody.create(json, MediaType.get("application/json;charset=UTF-8"));
        // 创建request, 表单提交
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        return exec(request);
    }

}
